package com.nuanshui.heatedloan.extension.shiro;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 生成验证码的servlet
 */
public class SimpleCaptchaServlet extends HttpServlet {
	/** 描述 */
	private static final long serialVersionUID = -314440845042577575L;
	private final int height = 24;
	private final int width = 75;
	private final int length = 4;

	public static final String CAPTCHA_KEY = "captcha_key";

	@Override
	public void init(final ServletConfig config) throws ServletException {
		super.init(config);
	}

	@Override
	protected void doGet(final HttpServletRequest req,
			final HttpServletResponse response) throws IOException,
			ServletException {
		// 首先设置页面不缓存
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setHeader("Pragma", "no-cache");
		response.setDateHeader("Max-Age", 0);

		final OutputStream outputStream = response.getOutputStream();
		// 创建一个图片对象
		final BufferedImage image = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_BGR);
		// 得到图像的环境对象
		final Graphics g = image.createGraphics();
		// 用随机颜色填充图像背景
		final Random random = new Random();
		g.setColor(getColor(180, 250));
		g.fillRect(0, 0, width, height);
		for (int i = 0; i < 5; i++) {
			g.setColor(getColor(50, 100));
			final int x = random.nextInt(width);
			final int y = random.nextInt(height);
			g.drawOval(x, y, 4, 4);
		}
		g.setFont(new Font("", Font.PLAIN, 28));
		// 随机字符串
		String sRand = "";
		for (int i = 0; i < length; i++) {
			final String rand = String.valueOf(random.nextInt(10));
			sRand += rand;
			// 天生随机颜色
			g.setColor(new Color(20 + random.nextInt(80), 20 + random
					.nextInt(100), 20 + random.nextInt(90)));
			g.drawString(sRand, 5, 25);
			// 天生干扰向
			for (int j = 0; j < 12; j++) {
				final int x = random.nextInt(width);
				final int y = random.nextInt(height);
				final int x1 = random.nextInt(9);
				final int y1 = random.nextInt(9);
				g.drawLine(x, y, x + x1, y + y1);
			}
		}
		// 使画像天生
		g.dispose();
		// 返回并设置session
		req.getSession().setAttribute(CAPTCHA_KEY, sRand);
		ImageIO.write(image, "jpeg", outputStream);
		outputStream.close();
	}

	/**
	 * 产生一个随机的颜色
	 * 
	 * @return
	 */
	public Color getColor(int fc, int bc) {
		final Random random = new Random();
		if (fc > 255) {
			fc = 255;
		}
		if (bc > 255) {
			bc = 255;
		}

		final int red = fc + random.nextInt(bc - fc);
		final int green = fc + random.nextInt(bc - fc);
		final int blue = fc + random.nextInt(bc - fc);

		return new Color(red, green, blue);
	}

}